package com.luo.stock.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luo.stock.service.UserService;
import com.luo.stock.vo.resp.PageResult;
import com.luohai.stock.constant.StockConstant;
import com.luohai.stock.mapper.SysRoleMapper;
import com.luohai.stock.mapper.SysUserMapper;
import com.luohai.stock.mapper.SysUserRoleMapper;
import com.luohai.stock.pojo.entity.SysPermission;
import com.luohai.stock.pojo.entity.SysRole;
import com.luohai.stock.pojo.entity.SysUser;
import com.luohai.stock.pojo.vo.*;
import com.luohai.stock.utils.IdWorker;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.luohai.stock.constant.StockConstant.CHECK_PREFIX;

/**
 * @Description
 * @Author 奥观海
 * @Date 2024/9/15
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
   @Autowired
   private PasswordEncoder passwordEncoder;
   @Autowired
   private RedisTemplate redisTemplate;
   @Autowired
   private IdWorker idWorker;
   @Autowired
   private SysRoleMapper sysRoleMapper;
   @Autowired
   private SysUserRoleMapper userRoleMapper;
   private Long userId;
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        if(vo==null|| StringUtils.isBlank(vo.getCode())||StringUtils.isBlank(vo.getUsername())){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        if(StringUtils.isBlank(vo.getPassword())){
            return R.error(ResponseCode.CHECK_CODE_NOT_EMPTY);
        }
        String rCode = (String) redisTemplate.opsForValue().get(CHECK_PREFIX + vo.getSessionId());
        if(StringUtils.isBlank(rCode) ||!rCode.equalsIgnoreCase(vo.getCode())){
            return R.error(ResponseCode.CHECK_CODE_ERROR);
        }
        SysUser user = sysUserMapper.findByUserName(vo.getUsername());
        if(user==null||passwordEncoder.matches(user.getPassword(),vo.getPassword())){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR.getMessage());
        }
        userId=user.getId();
        LoginRespVo respVo = new LoginRespVo();
        BeanUtils.copyProperties(user,respVo);
        return getmenus(respVo);
    }

    private R<LoginRespVo> getmenus(LoginRespVo respVo) {
        List<SysPermission> list=sysUserMapper.getmenus(respVo.getId());
        List<LoginChildren> childrens=new ArrayList<>();
        List<String> codeList = new ArrayList<>();
        if(CollectionUtils.isEmpty(list)){
            return R.ok(respVo);
        }
        for (SysPermission sysPermission : list) {
            if(sysPermission==null)continue;
            String s = sysPermission.getCode();
            if(!(s == null ||"".equals(s)))codeList.add(s);
            if(sysPermission.getPid()==0){
                LoginChildren loginChildren = new LoginChildren();
                BeanUtils.copyProperties(sysPermission,loginChildren);
                loginChildren.setPath(sysPermission.getUrl());
                childrens.add(loginChildren);
                getchildrens(sysPermission,list,loginChildren);
            }
        }
        respVo.setChildren(childrens);
        respVo.setPermissions(codeList);
        return R.ok(respVo);
    }
   private void getchildrens(SysPermission permission,List<SysPermission> list,LoginChildren children){
       for (SysPermission sysPermission : list) {
           if(sysPermission==null)continue;
           if(sysPermission.getPid().equals(permission.getId())){
               LoginChildren loginChildren = new LoginChildren();
               BeanUtils.copyProperties(sysPermission,loginChildren);
               loginChildren.setPath(sysPermission.getUrl());
               children.getChildren().add(loginChildren);
               getchildrens(sysPermission,list,loginChildren);
           }
       }
   }
    @Override
    public R<Map<String, String>> getCaptchaCode() {
        Map<String,String> map=new HashMap<>();
        String sessionId= String.valueOf(idWorker.nextId());
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(250, 40, 4, 5);
        //设置背景颜色清灰
        captcha.setBackground(Color.lightGray);
        String code = captcha.getCode();
        redisTemplate.opsForValue().set(StockConstant.CHECK_PREFIX+sessionId,code,1, TimeUnit.MINUTES);
        map.put("sessionId",sessionId);
        map.put("imageData",captcha.getImageBase64());
        return R.ok(map);
    }

    @Override
    public R<PageResult<SysUserVo>> getUsersPageVo(UsersPageVo usersPageVo) {
        PageHelper.startPage(usersPageVo.getPageNum(),usersPageVo.getPageSize());
        if(usersPageVo.getNickName()!=null&&!usersPageVo.getNickName().equals("")){
            usersPageVo.setNickName("%"+usersPageVo.getNickName()+"%");
        }
        if(usersPageVo.getUsername()!=null&&!usersPageVo.getUsername().equals("")){
            usersPageVo.setUsername("%"+usersPageVo.getUsername()+"%");
        }
        List<SysUserVo> list= sysUserMapper.getUsersPageVo(usersPageVo);
       if(CollectionUtils.isEmpty(list)){
           return R.error(ResponseCode.NO_RESPONSE_DATA);
       }

        PageResult<SysUserVo> result = new PageResult<>(new PageInfo<>(list));
        return R.ok(result);
    }

    @Override
    public R<String> addUser(SysUser sysUser) {
        SysUser byUserName = sysUserMapper.findByUserName(sysUser.getUsername());
        if(byUserName!=null){
            return R.error("账号重复");
        }
        long id = idWorker.nextId();
        sysUser.setId(id);
        sysUser.setCreateId(userId);
        sysUser.setUpdateId(userId);
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        int insert = sysUserMapper.insert(sysUser);
        if(insert==0){
            return R.error("添加失败");
        }
        return R.ok("添加成功");
    }

    @Override
    public R<RoleVo> getUserRole(String userId) {
        List<SysRole> allRole=sysRoleMapper.getAllRole();
        if(CollectionUtils.isEmpty(allRole)){
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        List<SysRole> ownRoles=sysRoleMapper.getOneRole(userId);
        RoleVo roleVo = new RoleVo();
        roleVo.setOwnRoles(ownRoles);
        roleVo.setAllRole(allRole);
        return R.ok(roleVo);
    }

    @Override
    public R<String> setRoles(String userId, List<String> roleIds) {
        Integer count=userRoleMapper.addUserAndRoles(idWorker.nextId(),userId,roleIds,new Date());
       if(count>0){
           return R.ok("添加成功");
       }
        return R.error("失败");
    }

    @Override
    public R<String> deleteUser(List<Long> userIds) {
        Integer count=sysUserMapper.deleteAllIds(userIds);
        if(count>0){
            return R.ok("添加成功");
        }
        return R.error("失败");
    }

    @Override
    public R<SysUserVo> getOneUser(String userId) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(Long.valueOf(userId));
        if(sysUser==null){
            R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        SysUserVo vo = new SysUserVo();
        BeanUtils.copyProperties(sysUser,vo);
        return R.ok(vo);
    }

    @Override
    public R<SysUserVo> updateOneUser(SysUser user) {
        int count = sysUserMapper.updateByPrimaryKeySelective(user);
        if(count>0){
            return R.ok("更改成功");
        }
        return R.error("更改失败");
    }


}
